package com.tdxy.game;

import lombok.Data;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class StarGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        MyPanel myPanel = new MyPanel() ;
        frame.setBounds(300,200,800,600);
        frame.add(myPanel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(3);
    }
}

class MyPanel extends JPanel{
    // 2. 创建300个星星
    Star stars [] ;
    Random ran ;

    public MyPanel() {
        ran = new Random();
        stars = new Star[300];
        Font font = new Font("微软雅黑",Font.BOLD , 30);
        for (int i = 0; i < stars.length; i++) {
            // 注意 : 数组的值, 需要new 来赋值
            Star star = new Star();
            star.setFont(font);
            Color color = new Color(ran.nextInt(256),ran.nextInt(256),ran.nextInt(256));
            star.setColor(color);
            star.setX(ran.nextInt(800));
            star.setY(ran.nextInt(600));
            // 给星星赋值后, 再添加进数组
            stars[i]  = star ;
        }

        new Thread(new Runnable() {
            public void run() {
                down();
            }
        }).start();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g); // 调用父类的 画画的方法
        g.setColor(Color.BLACK);
        g.fillRect(0,0,800,600);
        for (int i = 0; i < stars.length; i++) {
            Star star = stars[i];
            g.setColor(star.getColor());
            g.setFont(star.getFont());
            g.drawString(Star.content,star.getX(),star.getY());
        }

    }

    public void down (){
        while (true){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 0; i < stars.length; i++) {
                Star star = stars[i];
                int height = star.getY() ; // 目前星星的高度
                if(height > 580){
                    height = 0  ;
                }
                star.setY(height + 5);// 更改星星的高度
                stars[i] = star ;

            }

            repaint();// 重新进行绘画,
        }
    }

}
// 1. 定义星星类
@Data
class Star{
    public static String content = "*";

    private int x ;
    private int y ;
    private Color color ;
    private Font font ;
}